<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="`${isUpdate ? '编辑' : '添加'}权限组`"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #menu_ids="{ model, field }">
        <BasicTree
          ref="basicTreeRef"
          v-model:value="model[field]"
          :treeData="treeData"
          :checkedKeys="checkedKeys"
          :fieldNames="{ children:'children', label:'title', key: 'id' }"
          checkable
          toolbar
          title="菜单分配"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { formSchema } from './role.data';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { BasicTree, TreeItem } from '@/components/Tree';

  import {getAdminMenusOptions} from "@/api/common";
  import {createAdminGroup, updateAdminGroup} from "@/api/admin/admin_group";
  import { useMessage } from '@/hooks/web/useMessage';

  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const treeData = ref<TreeItem[]>([]);
  const checkedKeys = ref([]);
  const basicTreeRef = ref();
  const profile = ref();
  const { createMessage } = useMessage();

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields();
    setDrawerProps({ confirmLoading: false });
    // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
    profile.value = data.record;
    if (unref(treeData).length === 0) {
      const { result: { list } } = (await getAdminMenusOptions({ type: 'all' })) as any as TreeItem[];
      treeData.value = list;
    }
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      const { menu_ids = [] } = data.record;
      checkedKeys.value = menu_ids;
      await setFieldsValue({
        ...data.record,
      });
    }
  });

  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });

      //const { getCheckedKeys } = basicTreeRef.value;
      //const checkedKeys = getCheckedKeys();

      let data = null
      if (unref(isUpdate)) {
        data = (await updateAdminGroup({ ...values, id: profile.value.id })) as any
      } else {
        data = (await createAdminGroup(values)) as any
      }

      if (!data.code) {
        createMessage.success(`设置成功！`)
        emit('success', {})
        closeDrawer()
      } else {
        createMessage.warn(`设置失败！`)
      }

      // TODO custom api
      console.log(values);
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
